5.2 - Playing a custom sound in game


This is our freshly created mod project:


using SonsSdk;

namespace SoundMod;

public class SoundMod : SonsMod
{
    public SoundMod()
    {

        //HarmonyPatchAll = true;
    }

    protected override void OnInitializeMod()
    {
        Config.Init();
    }

    protected override void OnSdkInitialized()
    {
        SoundModUi.Create();
    }

    protected override void OnGameStart()
    {
    }
}
            

Registering sounds

To play a soundfile in the game, we first need to register it.
This needs to be done inside the OnSdkInitialized method following the code below:

  • First parameter: it's the identifier of the sound as a string. This is what we will use to specify what sound to play
  • Second parameter: it's the path to the sound file we want to register with that ID


protected override void OnSdkInitialized()
{
    SoundTools.RegisterSound("soundId", "pathOfTheFile");
}
            

If we want the sound to be 3Dimensional, and so hearing it at a certain game position, we need to pass true as the third method parameter:


protected override void OnSdkInitialized()
{
    SoundTools.RegisterSound("soundId", "pathOfTheFile", true);
}
            

Assuming we have our sound file in the Mods folder we will register it like so:


protected override void OnSdkInitialized()
{
    SoundTools.RegisterSound("soundId", Path.Combine(LoaderEnvironment.ModsDirectory, "soundfile.mp3"));
}
            

Playing the sound

To play the registered sounds we just need to do like so wherever we want in code:


protected override void OnGameStart()
{
    SoundTools.PlaySound("soundId");
}
            

If the sound was registered as 3Dimensional we will also need to pass a position as Vector3 and and the maximum distance at which it can be heard:


protected override void OnGameStart()
{
    // playing a sound a position 0 audible up to 10m distance
    SoundTools.PlaySound("soundId", new Vector3(0, 0, 0), 10);
}